<template>
    <n-grid :cols="12" item-responsive responsive="screen">
        <n-gi span="12 m:8 l:6" offset="0 m:2 l:3">
            <n-form :model="formParams" :rules="rules" ref="formRef">
                <n-form-item label="标题" path="title">
                    <n-input v-model:value="formParams.title"></n-input>
                </n-form-item>
                <n-form-item label="类型" path="type">
                    <n-select v-model:value="formParams.type" :options="examTypeOptions" />
                </n-form-item>
                <n-form-item label="开始时间" path="startTime">
                    <n-date-picker v-model:value="formParams.startTime"></n-date-picker>
                    <n-time-picker v-model:value="formParams.startTime"></n-time-picker>
                </n-form-item>
                <n-form-item label="结束时间" path="endTime">
                    <n-date-picker v-model:value="formParams.endTime"></n-date-picker>
                    <n-time-picker v-model:value="formParams.endTime"></n-time-picker>
                </n-form-item>
                <n-form-item label="积分" path="credit">
                    <n-input-number v-model:value="formParams.credit" :min="0"></n-input-number>
                </n-form-item>
                <n-form-item label="题目">
                    <n-collapse :default-expanded-names="['1', '2', '3', '4', '5']" style="width:100%">
                        <n-collapse-item title="单选" name="1">
                            <n-space vertical>
                                <n-space inline>
                                    <n-text>批量设置分数</n-text>
                                    <n-input-number v-model:value="score[0]" :min="0"></n-input-number>
                                    <n-button @click="handleSetScore(0)">确定</n-button>
                                </n-space>

                                <template v-for="questions in questionSelectedList">
                                    <div v-if="questions.type == 0">
                                        <n-space inline>
                                            <n-text>题号：{{ questions.QID }}</n-text>
                                            <n-ellipsis style="width: 100px">{{ questions.title }}</n-ellipsis>
                                            <n-input-number v-model:value="questions.score" :min="0"
                                                placeholder="请输入分数"></n-input-number>
                                            <n-button @click="delete questionSelectedList[questions.QID]">删除</n-button>
                                        </n-space>
                                    </div>
                                </template>
                            </n-space>
                        </n-collapse-item>
                        <n-collapse-item title="多选" name="2">
                            <n-space vertical>
                                <n-space inline>
                                    <n-text>批量设置分数</n-text>
                                    <n-input-number v-model:value="score[1]" :min="0"></n-input-number>
                                    <n-button @click="handleSetScore(1)">确定</n-button>
                                </n-space>
                                <template v-for="questions in questionSelectedList">
                                    <div v-if="questions.type == 1">
                                        <n-space inline>
                                            <n-text>题号：{{ questions.QID }}</n-text>
                                            <n-ellipsis style="width: 100px">{{ questions.title }}</n-ellipsis>
                                            <n-input-number v-model:value="questions.score" :min="0"
                                                placeholder="请输入分数">
                                            </n-input-number>
                                            <n-button @click="delete questionSelectedList[questions.QID]">删除</n-button>
                                        </n-space>
                                    </div>
                                </template>
                            </n-space>
                        </n-collapse-item>
                        <n-collapse-item title="判断" name="3">
                            <n-space vertical>
                                <n-space inline>
                                    <n-text>批量设置分数</n-text>
                                    <n-input-number v-model:value="score[2]" :min="0"></n-input-number>
                                    <n-button @click="handleSetScore(2)">确定</n-button>
                                </n-space>
                                <template v-for="questions in questionSelectedList">
                                    <div v-if="questions.type == 2">
                                        <n-space inline>
                                            <n-text>题号：{{ questions.QID }}</n-text>
                                            <n-ellipsis style="width: 100px">{{ questions.title }}</n-ellipsis>
                                            <n-input-number v-model:value="questions.score" :min="0"
                                                placeholder="请输入分数">
                                            </n-input-number>
                                            <n-button @click="delete questionSelectedList[questions.QID]">删除</n-button>
                                        </n-space>
                                    </div>
                                </template>
                            </n-space>
                        </n-collapse-item>
                        <n-collapse-item title="填空" name="4">
                            <n-space vertical>
                                <n-space inline>
                                    <n-text>批量设置分数</n-text>
                                    <n-input-number v-model:value="score[3]" :min="0"></n-input-number>
                                    <n-button @click="handleSetScore(3)">确定</n-button>
                                </n-space>
                                <template v-for="questions in questionSelectedList">
                                    <div v-if="questions.type == 3">
                                        <n-space inline>
                                            <n-text>题号：{{ questions.QID }}</n-text>
                                            <n-ellipsis style="width: 100px">{{ questions.title }}</n-ellipsis>
                                            <n-input-number v-model:value="questions.score" :min="0"
                                                placeholder="请输入分数">
                                            </n-input-number>
                                            <n-button @click="delete questionSelectedList[questions.QID]">删除</n-button>
                                        </n-space>
                                    </div>
                                </template>
                            </n-space>
                        </n-collapse-item>
                        <n-collapse-item title="主观" name="5">
                            <n-space vertical>
                                <n-space inline>
                                    <n-text>批量设置分数</n-text>
                                    <n-input-number v-model:value="score[4]" :min="0"></n-input-number>
                                    <n-button @click="handleSetScore(4)">确定</n-button>
                                </n-space>
                                <template v-for="questions in questionSelectedList">
                                    <div v-if="questions.type == 4">
                                        <n-space inline>
                                            <n-text>题号：{{ questions.QID }}</n-text>
                                            <n-ellipsis style="width: 100px">{{ questions.title }}</n-ellipsis>
                                            <n-input-number v-model:value="questions.score" :min="0"
                                                placeholder="请输入分数">
                                            </n-input-number>
                                            <n-button @click="delete questionSelectedList[questions.QID]">删除</n-button>
                                        </n-space>
                                    </div>
                                </template>
                            </n-space>
                        </n-collapse-item>
                    </n-collapse>
                </n-form-item>
                <n-form-item>
                    <n-space inline>
                        <n-button type="primary" @click="confirmForm">提交</n-button>
                        <n-button @click="() => { router.go(-1) }">返回</n-button>
                    </n-space>
                </n-form-item>
                <!-- {{ JSON.stringify(formParams) }} -->
            </n-form>
        </n-gi>
        <n-gi span="12 m:10" offset="0 m:1">
            <n-card>
                <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
                    <template #statusSlot="{ model, field }">
                        <n-input v-model:value="model[field]" />
                    </template>
                </BasicForm>
                <BasicTable title="选择你想要的题目" titleTooltip="关注永雏塔菲喵，关注永雏塔菲谢谢喵" :columns="columns"
                    :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef" :actionColumn="actionColumn"
                    :scroll-x="1360" @update:checked-row-keys="onCheckedRow">
                    <template #toolbar>
                        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
                    </template>
                </BasicTable>
                <!-- {{ JSON.stringify(formParams.questions) }} -->

            </n-card>

        </n-gi>
    </n-grid>
</template>
<script lang="ts" setup>

import { columns } from '../question/questionColumns';
import { getTableList, getTagList } from '@/api/teacher/question';
import { BasicTable, TableAction } from '@/components/Table';
import { h, reactive, ref,onMounted } from 'vue';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { useRoute, useRouter } from 'vue-router';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { http } from '@/utils/http/axios';
import { useMessage } from 'naive-ui';
import {getExam} from '@/api/teacher/exam';


const examTypeOptions = [
    {
        label: '多次提交',
        value: '0',
    }, {
        label: '一次提交',
        value: '1',
    }
]

const questionSelectedList: any = reactive({});

const route = useRoute();
const router = useRouter();
onMounted(async () => {
    let params = await getExam({ EID: route.params.EID });
    formParams.title = params.title;
    formParams.type = params.type.toString();
    formParams.startTime = new Date(params.startTime).getTime();
    formParams.endTime = new Date(params.endTime).getTime();
    formParams.questions = params.questions;
    formParams.credit = params.credit;
    formParams.courseID = params.courseID;
    for(let question in params.questions){
        questionSelectedList[question.toString()] = params.questions[question];
    }
    console.log(questionSelectedList);
});

const tagOptions = ref();

const actionRef = ref();

const actionColumn = reactive({
    width: 20,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
        return h(TableAction, {
            style: 'button',
            actions: createActions(record),
        });
    },
});
const formParams: any = reactive({
    title: null,
    type: null,
    startTime: null,
    endTime: null,
    questions: null,
    credit: null,
    courseID: route.params.courseID
});

const score = ref([0, 0, 0, 0, 0]);
function handleSetScore(type) {
    for (let questions in questionSelectedList) {
        console.log(questionSelectedList);
        console.log(type);
        if (questionSelectedList[questions]['type'] == type) {
            console.log(questionSelectedList);
            questionSelectedList[questions]['score'] = score.value[type];
        }
    }

}

function createActions(record) {
    return [
        {
            label: '添加',
            icon: 'ic:outline-delete-outline',
            onClick: handleAddQustion.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
                return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['basic_list'],
        },
    ];
}


function onCheckedRow(rowKeys) {
    console.log(rowKeys);
}


const handleAddQustion = (record) => {
    questionSelectedList[record.QID.toString()] = {
        QID: record.QID,
        type: record.type,
        title: record.title,
        score: 0
    };
}


const params = reactive({
    pageSize: 10,
    courseID: route.params.courseID,
    QID: null,
    tag: null,
    type: null
});

const loadDataTable = async (res) => {
    let tagResult = await getTagList({ ...params });
    tagOptions.value = [];
    tagResult.forEach(element => {
        tagOptions.value.push(
            {
                value: element['tag'],
                label: element['tag']
            }
        )
    });
    return await getTableList({ ...params, ...res });
};

function reloadTable() {
    actionRef.value.reload();
}



const schemas: FormSchema[] = [
    {
        field: 'QID',
        component: 'NInputNumber',
        label: '题目号号',
        componentProps: {
            placeholder: '请输入题号',
            showButton: false,
            onInput: (e: any) => {
                console.log(e);
            },
        },
    },
    {
        field: 'type',
        component: 'NSelect',
        label: '类型',
        componentProps: {
            placeholder: '请选择题目类型',
            //remote:true,
            value: ref(null),
            options: [
                {
                    value: '0',
                    label: '单选',
                },
                {
                    value: '1',
                    label: '多选',
                },
                {
                    value: '2',
                    label: '判断',
                },
                {
                    value: '3',
                    label: '填空',
                }, {
                    value: '4',
                    label: '简答',
                }

            ],
        }
    },
    {
        field: 'tag',
        component: 'NSelect',
        label: '标签',
        componentProps: {
            placeholder: '请选择题目标签',
            //remote:true,
            value: ref(null),
            options: tagOptions,
        }
    }
]


const [register] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:4 xl:5 2xl:5' },
    labelWidth: 80,
    schemas,
});

function handleSubmit(values: Recordable) {
    params['type'] = values['type'];
    params['QID'] = values['QID'];
    params['tag'] = values['tag'];
    reloadTable();
}

function handleReset(values: Recordable) {
    console.log(values);
}

const rules = {
    title: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入标题',
    },
    type: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入类型',
    },
    startTime: {
        required: true,
        type: 'number',
        trigger: ['blur', 'input'],
        message: '请输入开始时间',
    },
    endTime: {
        required: true,
        type: 'number',
        trigger: ['blur', 'input'],
        message: '请输入结束时间',
    },
    credit: {
        required: true,
        type: 'number',
        trigger: ['blur', 'input'],
        message: '请输入积分',
    },
}

const formRef = ref();
const message = useMessage();

function confirmForm(e) {
    e.preventDefault();
    formRef.value.validate((errors) => {
        if (!errors) {
            //message.success('新建成功');
            let params = formParams;
            params.questions = Object.values(questionSelectedList);
            params.EID = route.params.EID;
            http.request({
                url: '/teacher/teacher_exam/edit',
                method: 'post',
                params
            }).then(
                () => {
                    message.success('成功');
                    router.go(-1);
                }
            );
        } else {
            message.error('请填写完整信息');
        }
    });
}
</script>